// pages/yes/index.js
const http = require('../../api/index')
const request = require('../../utils/request')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    typename:'camp_camp_camptype_status',
    showtype: false,
    camptype: null,
    camptypelist: [],
    campLocation:'',
    latitude:'',
    longitude:'',
    address: null,
    time:'',//营业时间
    contacts:'',//联系人
    phone:'',//联系电话
    introduce:'',//营地内容
    timeType:'1',
    campId:'',
    facilityIds:[],
    showadress: false,
    //弹出层
    price: '250',
    checked: true,
    //步骤条
    active: 0,
    //初始为第一页
    viewshow: 1,
    //步骤条
    steps: [{
        text: '营地信息'
      },
      {
        text: '服务设施'
      }
    ],
    facility: [],
    facilityList: [],
    imgUrl: request.baseURL,
    selectFacilitiesList: [],
    introduce: "", 
    campImgs: [], 
    fileList: [],
    baseURL:request.baseURL,
    camptypeSelect:[
      // { dictLabel: '' }
    ]
    
  },
  getUploadList(l) {
    this.setData({
      campImgs: l.detail,
      tourisCampImgs: l.detail
    })
  },  
  addCamp(){
  },
  //上一步
  btnPre() {
    var newActive = --this.data.active;
    var newViewshow = --this.data.viewshow;
    if (newActive >= 0) {
      this.setData({
        active: newActive,
        viewshow: newViewshow
      })
    }
  },
  delImgs(u) {
    this.data.campImgs.splice(u.currentTarget.dataset.index, 1)
    this.setData({
      campImgs: this.data.campImgs
    })
  },
  //下一步
  btnNext() {
    var newActive = ++this.data.active;
    var newViewshow = ++this.data.viewshow;
    if (newActive >= 3) {
      wx.showToast({
          icon: 'none',
          title: '这就是最后一页！！',
          duration: 1500
        })
        --this.data.active;
      --this.data.viewshow;
    } else {
      this.setData({
        active: newActive,
        viewshow: newViewshow
      })
    }
  },
  //弹出层的显示与关闭
  showPopup() {
    this.setData({
      showtype: true
    });
  },
  onClose() {
    this.setData({
      showtype: false,
      camptype: null
    });
  },
  onChange(e) {
    this.setData({
      timeType: e.detail
    })
    if (e.detail == 1) {
      this.setData({
        timeDetailOpen: false,
        time: "全年"
      })
    } else {
      this.setData({
        timeDetailOpen: true
      })
    }
  },
  onChange(event) {
    const {
      value
    } = event.detail;
    this.setData({
      camptype: value
    });
  },
  onChangeType(event){
    const {
      value
    } = event.detail;
    this.setData({
      camptype: value
    });
  },
  onConfirm() {
    this.setData({
      showtype: false,
    });
  },
  //单选按钮点击
  onClick(event) {
    const {
      name
    } = event.currentTarget.dataset;
    this.setData({
      camptype: name,
    });
  },
  //跳转到地图组件
  tomap() {
    wx.navigateTo({
      url: '/components/campmap-checkbox/campmap-checkbox?pageStatus=0',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getDict(this.data.typename);s
     this.getUserType();
    this.setData({
      campLocation: options.addr,
      latitude:options.latitude,
      longitude:options.longitude,
    })
    
    this.getfacility();
  },
   getUserType(){
    let that = this;
    console.log('that',that);
    wx.getStorage({
      key: 'userTypeId',
      success(res) {
        that.setData({
          userType:res.data.userType
        })
   
      },
      fail(err) {
        console.error('缓存读取失败：', err);
      },
    });
    
  },
  getDict(e) {
    console.log("getDict");
    http.dictList(e).then(res=>{
      console.log('res',res)
      if(res.code === 200){    
        this.setData({
          camptypelist: res.data
      })   
      // this.data.camptypeSelect = 
      this.setData({
        camptypeSelect: this.data.camptypelist.map(item => item.dictLabel)
      })
      console.log('camptypeSelect', this.data.camptypeSelect)
      }   
    })
 
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getDict(this.data.typename);
  },
  // 获取设施列表
  getfacility() {
    http.facilityTypeList().then((res) => {

      if (res.code === 200) {
        this.setData({
          facility: res.rows,
        })
        console.log('facility', this.data.facility);
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  selectIcon(e) {
    let a, b, select, list, id, data
    list = this.data.facility
    id = e.currentTarget.dataset.id
    data = this.data.selectFacilitiesList
    for (let i = 0; i < list.length; i++) {
      for (let j = 0; j < list[i].facilities.length; j++) {
        if (id == list[i].facilities[j].facilityId) {
          a = i
          b = j
        }
      }
    }
    select = list[a].facilities[b].state

    if (select == 1) {
      list[a].facilities[b].state = 2

      data.push(id)
      this.setData({
        facility: list,
        selectFacilitiesList: data
      })

    } else {
      list[a].facilities[b].state = 1
      let index = data.indexOf(id)
      data.splice(index, 1)
      this.setData({
        facility: list,
        selectFacilitiesList: data
      })
    }



  },
  async readStorage(){
    let that =this;
    
    wx.getStorage({
      key: 'userTypeId', // 缓存的键
      success(res) {
        console.log('读取成功，值为：', res.data); // 缓存中的值
        that.setData({
          userType: res.data.userType
        })
      },
      fail(err) {
        console.error('读取失败：', err);
      }
    });

  },
   // 运营者提交数据
   async businessSub() {
     
    await this.readStorage()
    await this.subCamp()
    await this.subService()
    
  },
   // 提交营地信息
  async subCamp() {
    let userInfo = wx.getStorageSync("userInfo")
    let campType = this.campType(this.data.type)
    let res = await http.addCamp({
      userId: userInfo.userId,
      userType: this.data.userType,
      campType,
      campName: this.data.name,
      longitude: this.data.longitude, //经度
      latitude: this.data.latitude,
      location: this.data.campLocation,
      address: this.data.address,
      timeType: this.data.timeType,
      specificTime: this.data.time,
      linkman: this.data.contacts,
      phone: this.data.phone,
      imageUrl: this.data.campImgs.join(","),
      introduce: this.data.introduce,
     
    })
    this.setData({
      campId: res.msg
    })
  },
  // 返回营地类型id
  campType(value) {
    return this.data.camptypeSelect.indexOf(value) + 1
  },
    // 上传服务设施
    async subService() {
      let res = await http.addFacility({
        campId: this.data.campId,
        facilityIds: this.data.selectFacilitiesList
      })
      console.log('code',res.code)
      console.log('res',res);
      if (res.code == 200) {
        console.log('跳转');
        wx.switchTab({
          url: '/pages/index/index',
        })
        console.log('跳转2');
      }
    },
      //营业时间
  selectTime() {
    this.setData({
      open: false,
      timeOpen: true,
      time: "全年"
    })
  },
  // 关闭时间
  closeTime() {
    this.setData({
      timeOpen: false
    })
  },
  // 确定时间
  sureTime() {
    this.setData({
      timeOpen: false
    })
    console.log(this.data.time)
  },
  

})